//
//  UIScrollView+SEGSWindmill.m
//  RefreshDemo
//
//  Created by Clavis on 2019/1/2.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "UIScrollView+SEGSwindmill.h"
#import <objc/runtime.h>

@interface UIScrollView ()
@property (nonatomic, strong) NSDate *startRefreshTime; // 上次刷新的时间
@end

@implementation UIScrollView (SEGSWindmill)

- (void)setStartRefreshTime:(NSDate *)startRefreshTime {
    objc_setAssociatedObject(self, _cmd, startRefreshTime, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSDate *)startRefreshTime {
    return objc_getAssociatedObject(self, @selector(setStartRefreshTime:));
}

- (void)setSeg_header:(SEGWindmillRefreshCommonHeader *)seg_header {
    if (seg_header != self.seg_header) {
        [self.seg_header removeFromSuperview];
        [self insertSubview:seg_header atIndex:0];
        
        [self willChangeValueForKey:@"seg_header"];
        objc_setAssociatedObject(self, _cmd, seg_header, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"seg_header"];
    }
}

- (SEGWindmillRefreshCommonHeader *)seg_header {
    return objc_getAssociatedObject(self, @selector(setSeg_header:));
}

- (void)setSeg_footer:(SEGWindmillRefreshCommonFooter *)seg_footer {
    if (seg_footer != self.seg_footer) {
        [self.seg_footer removeFromSuperview];
        [self insertSubview:seg_footer atIndex:0];
        
        [self willChangeValueForKey:@"seg_footer"];
        objc_setAssociatedObject(self, _cmd, seg_footer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"seg_footer"];
    }
}

- (SEGWindmillRefreshCommonFooter *)seg_footer {
    return objc_getAssociatedObject(self, @selector(setSeg_footer:));
}

- (void)addWindmillWithHeaderRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)headerRefreshBlock {
    self.seg_header = [SEGWindmillRefreshCommonHeader headerWithRefreshingBlock:headerRefreshBlock];
}

- (void)addWindmillWithFooterRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)footerRefreshBlock {
    self.seg_footer = [SEGWindmillRefreshCommonFooter footerWithRefreshingBlock:footerRefreshBlock];
    
//    NSLog(@"header = %@", self.seg_header);
//    NSLog(@"footer = %@", self.seg_footer);
}

- (void)addWindmillWithHeaderRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)headerRefreshBlock footerRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)footerRefreshBlock {
    self.seg_header = [SEGWindmillRefreshCommonHeader headerWithRefreshingBlock:headerRefreshBlock];
    self.seg_footer = [SEGWindmillRefreshCommonFooter footerWithRefreshingBlock:footerRefreshBlock];
}

- (void)startHeaderAnimatingWindmill {
    // 记录当前时间
    self.startRefreshTime = [NSDate date];
    
    
    // 为了兼容之前的逻辑，在第一次自动触发下拉刷新的时候，去调用VC实现的代理方法，传入刷新block进来
    SEL selector = @selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:);
    if ([self.viewController respondsToSelector:selector]) {
        IMP imp = [self.viewController methodForSelector:selector];
        CGRect (*func)(id, SEL, UIScrollView *, CGPoint, CGPoint *) = (void *)imp;
        func(self.viewController, selector, self, CGPointZero, nil);
    }
    [self.seg_header beginRefreshing];
}

- (void)startFooterAnimatingWindmill {
    [self.seg_footer beginRefreshing];
}

- (void)stopAnimatingWindmill {
    [self stopHeaderAnimatingWindmill];
    [self stopFooterAnimatingWindmill];
}

- (void)stopHeaderAnimatingWindmill {
//    NSDate *stopRefreshTime = [NSDate date];
//    NSTimeInterval timeInterval = stopRefreshTime.timeIntervalSinceNow - self.startRefreshTime.timeIntervalSinceNow;
//    NSLog(@"timeInterval = %lf", timeInterval);
//    
//    if (timeInterval < SEGRefreshMinAnimationDuration) {
//        NSTimeInterval delayInSeconds = SEGRefreshMinAnimationDuration - timeInterval;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.seg_header endRefreshing];
//        });
//        return;
//    }
//    
    [self.seg_header endRefreshing];
}

- (void)stopFooterAnimatingWindmill {
    [self.seg_footer endRefreshing];
}

#pragma mark - other

- (NSInteger)seg_totalDataCount {
    NSInteger totalCount = 0;
    if ([self isKindOfClass:[UITableView class]]) {
        UITableView *tableView = (UITableView *)self;
        
        for (NSInteger section = 0; section<tableView.numberOfSections; section++) {
            totalCount += [tableView numberOfRowsInSection:section];
        }
    } else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
        
        for (NSInteger section = 0; section<collectionView.numberOfSections; section++) {
            totalCount += [collectionView numberOfItemsInSection:section];
        }
    }
    return totalCount;
}

- (void)setSeg_totalDataCount:(NSInteger)seg_totalDataCount {
    
}

#pragma mark - 兼容之前的API
//在viewDidLoad或viewDidAppare中调用此方法,放在父view加tableview之前, 会同时添加上拉和下拉
-(void)addWindmillInSuperView:(UIView *)superView {
    self.seg_header = [SEGWindmillRefreshCommonHeader headerWithRefreshingBlock:^{
        NSLog(@"====  header refresh");
    }];
    self.seg_footer = [SEGWindmillRefreshCommonFooter footerWithRefreshingBlock:^{
        NSLog(@"====  footer refresh");
    }];
}

//将此方法放在scrollViewDidScroll:中
-(void)draggingScrollViewInOffsety:(CGFloat)offsety {
    
}

//canHeaderFresh是否需要刷新数据和界面
-(void)startAnimatingWindmill:(void(^)(BOOL canHeaderFresh, BOOL isFooter))canfreshBlock {
    self.seg_header.refreshingBlock = ^{
        NSLog(@"000  header refresh");
        canfreshBlock(YES, NO);
    };
    
    self.seg_footer.refreshingBlock = ^{
        NSLog(@"000  footer refresh");
        canfreshBlock(YES, YES);
    };
}

- (void)justShowHeader {
    self.seg_footer = nil;
}

- (void)justShowfooter {
    self.seg_header = nil;
}

- (void)justStartAnimatingWindmill {
    
    
    [self startHeaderAnimatingWindmill];
}

@end
